package com.windoent.yugioh.ui.activity.saishi;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.baidu.mobstat.StatService;
import com.windoent.yugioh.R;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.JingWeiBean;
import com.windoent.yugioh.help.mengceng.NewbieGuide;
import com.windoent.yugioh.help.mengceng.model.GuidePage;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.inteface.CitySelectInterface;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.CreateGameStackUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.utils.some.utilcode.util.LogUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.RadioGroupSelectSingleButton;
import com.windoent.yugioh.widget.UserInfoItem;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import cn.qqtheme.framework.picker.DatePicker;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/11 14:57
 * desc   :比赛管理-创建比赛--申请比赛
 */
public class CreateGamesActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private LinearLayout mLlShuoming;
    private Button mBtnGetCode;
    private UserInfoItem mItemName;
    private UserInfoItem mItemTime;
    private UserInfoItem mItemArea;
    private UserInfoItem mItemAreaDetail;
    private UserInfoItem mItemNumber;
    private UserInfoItem mItemCost;
    private UserInfoItem mItemPhone;
    private RadioGroupSelectSingleButton mRadioType;
    private RadioGroupSelectSingleButton mRadioEnvironment;
    private RadioGroupSelectSingleButton mRadioFormat;
    private LinearLayout mLlLunNumbers;
    private TextView mTvLinNumbers;
    private ImageView mIvShuoming;
    private LinearLayout mLlTopNumbers;
    private TextView mTvTopNumbers;
    private String timeStamp;//开始时间时间戳
    private String zone_id;
    private String city_id;
    private String county_id;

    @Override
    public int getLayout() {
        return R.layout.activity_create_games;
    }

    @Override
    public void initView() {
        super.initView();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mLlShuoming = (LinearLayout) findViewById(R.id.ll_shuoming);
        mIvShuoming = (ImageView) findViewById(R.id.iv_shuoming);
        mBtnGetCode = (Button) findViewById(R.id.btn_get_code);
        mItemName = (UserInfoItem) findViewById(R.id.item_name);
        mItemTime = (UserInfoItem) findViewById(R.id.item_time);
        mItemArea = (UserInfoItem) findViewById(R.id.item_area);
        mItemAreaDetail = (UserInfoItem) findViewById(R.id.item_area_detail);
        mItemNumber = (UserInfoItem) findViewById(R.id.item_number);
        mItemCost = (UserInfoItem) findViewById(R.id.item_cost);
        mItemPhone = (UserInfoItem) findViewById(R.id.item_phone);
        mRadioType = (RadioGroupSelectSingleButton) findViewById(R.id.radio_type);
        mRadioEnvironment = (RadioGroupSelectSingleButton) findViewById(R.id.radio_environment);
        mRadioFormat = (RadioGroupSelectSingleButton) findViewById(R.id.radio_format);
        mLlLunNumbers = (LinearLayout) findViewById(R.id.ll_lun_numbers);
        mTvLinNumbers = (TextView) findViewById(R.id.tv_lin_numbers);
        mLlTopNumbers = (LinearLayout) findViewById(R.id.ll_top_numbers);
        mTvTopNumbers = (TextView) findViewById(R.id.tv_top_numbers);

    }

    @Override
    public void initData() {
        super.initData();
        CreateGameStackUtils.getInstance().addActivity(this);
        mTvLinNumbers.setText(getText(R.string.string_eight));
        mTvTopNumbers.setText(getText(R.string.string_four));
        guide(mIvShuoming);
    }

    //蒙层
    private void guide(ImageView imageView) {
        NewbieGuide.with(CreateGamesActivity.this)
                .setLabel("guide")
                .alwaysShow(false)//总是显示，调试时可以打开
                .addGuidePage(GuidePage.newInstance()
                        .addHighLight(imageView)
                        .setLayoutRes(R.layout.view_guide_simple_create_games))
                .show();
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mLlShuoming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //说明
                startActivity(new Intent(mContext, CreateGamesShuoMingActivity.class));
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shangjiaCreateGame();
            }
        });
        mItemTime.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //时间
                showTimeSelectDialog(mItemTime.getTextView());
            }
        });
        mItemArea.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //地区
                BaseMethod.cityPicker(CreateGamesActivity.this, mItemArea.getTextView(), "", "", "", "", "", "", new CitySelectInterface() {
                    @Override
                    public void getId(String zoneid, String cityid, String countyid) {
                        zone_id = zoneid;
                        city_id = cityid;
                        county_id = countyid;
                    }
                });
            }
        });
        mLlLunNumbers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //瑞士轮
                int checked = mRadioType.getChecked();
                if (BaseMethod.notNull(checked + "") && checked == 0) {//娱乐赛30.积分赛7
                    BaseMethod.onNumberPicker(CreateGamesActivity.this, 30, mTvLinNumbers);
                } else BaseMethod.onNumberPicker(CreateGamesActivity.this, 7, mTvLinNumbers);
            }
        });
        mLlTopNumbers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //出四强
                int checked = mRadioType.getChecked();
                if (BaseMethod.notNull(checked + "") && checked == 0) {//娱乐赛
                    BaseMethod.selectLunsStrong(CreateGamesActivity.this, mTvTopNumbers);
                } else
                    BaseMethod.onOptionStrongPicker(CreateGamesActivity.this, mTvTopNumbers);
            }
        });
        mRadioType.setOnclickListener(new RadioGroupSelectSingleButton.onClickListener() {
            @Override
            public void onClick(int position) {
                boolean showThree = BaseMethod.notNull(position + "") && position == 1;
                mRadioFormat.setOnLyJiFentaoTaiRadio(showThree);
                mLlLunNumbers.setVisibility(View.VISIBLE);
                if (showThree) {
                    mLlTopNumbers.setVisibility(View.VISIBLE);
                    mTvLinNumbers.setText(getText(R.string.string_eight));
                    mTvTopNumbers.setText(getText(R.string.string_four));
                } else {
                    mLlTopNumbers.setVisibility(View.GONE);
                    mTvLinNumbers.setText(getText(R.string.string_eight));
                    mTvTopNumbers.setText("");
                }
            }
        });
        mRadioFormat.setOnclickListener(new RadioGroupSelectSingleButton.onClickListener() {
            @Override
            public void onClick(int position) {
                if (BaseMethod.notNull(position + "") && position == 0) {
                    mLlLunNumbers.setVisibility(View.VISIBLE);
                    mLlTopNumbers.setVisibility(View.GONE);
                    mTvLinNumbers.setText(getText(R.string.string_eight));
                    mTvTopNumbers.setText("");
                } else if (BaseMethod.notNull(position + "") && position == 1) {
                    mLlLunNumbers.setVisibility(View.GONE);
                    mLlTopNumbers.setVisibility(View.GONE);
                    mTvLinNumbers.setText("");
                    mTvTopNumbers.setText("");
                } else if (BaseMethod.notNull(position + "") && position == 2) {
                    mLlLunNumbers.setVisibility(View.VISIBLE);
                    mLlTopNumbers.setVisibility(View.VISIBLE);
                    mTvLinNumbers.setText(getText(R.string.string_eight));
                    mTvTopNumbers.setText(getText(R.string.string_four));
                }
            }
        });

    }

    private void shangjiaCreateGame() {
        String name = mItemName.getEtContent();
        String start_at = mItemTime.getTvContent();
        String address = mItemArea.getTvContent();
        String addressDetails = mItemAreaDetail.getEtContent();
        String players = mItemNumber.getEtContent();
        String cost = mItemCost.getEtContent();
        String contact = mItemPhone.getEtContent();
        String type = getRadioType(mRadioType.getChecked());
        String condition = getRadioCondition(mRadioEnvironment.getChecked());
        String rule = getRadioRule(mRadioFormat.getChecked());
        String rounds = mTvLinNumbers.getText().toString().trim();
        String winning = mTvTopNumbers.getText().toString().trim();
        boolean notEmpty = notEmpty(name, start_at, address, addressDetails, players, cost, contact, type, condition, rule, rounds, winning);
        if (notEmpty) {
            getLatlon(addressDetails, name, timeStamp + "", players, cost, contact, type, condition, rule, rounds, winning, zone_id, city_id, county_id);
        }
    }

    private boolean notEmpty(String name, String start_at, String address, String addressDetails, String players, String cost, String contact, String type, String condition, String rule, String rounds, String winning) {
        if (BaseMethod.isNull(name)) {
            ToastUtils.showText(getString(R.string.string_create_games_name_null));
            return false;
        } else if (BaseMethod.isNull(start_at)) {
            ToastUtils.showText(getString(R.string.string_create_games_time_null));
            return false;
        } else if (BaseMethod.isNull(address)) {
            ToastUtils.showText(getString(R.string.string_create_games_address_null));
            return false;
        } else if (BaseMethod.isNull(addressDetails)) {
            ToastUtils.showText(getString(R.string.string_address_details_null));
            return false;
        } else if (BaseMethod.isNull(players)) {
            ToastUtils.showText(getString(R.string.string_create_games_players_null));
            return false;
        } else if (BaseMethod.isNull(cost)) {
            ToastUtils.showText(getString(R.string.string_create_games_cost_null));
            return false;
        } else if (BaseMethod.isNull(contact)) {
            ToastUtils.showText(getString(R.string.string_input_game_phone_hint));
            return false;
        } else if (BaseMethod.isNull(contact)) {
            ToastUtils.showText(getString(R.string.string_input_game_phone_hint));
            return false;
        }
        return true;
    }

    //赛事类型 (1:娱乐赛2：积分赛)
    private String getRadioType(int checked) {
        if (BaseMethod.notNull(checked + "") && checked == 0) {
            return "1";
        }
        if (BaseMethod.notNull(checked + "") && checked == 1) {
            return "2";
        }
        return "";
    }

    //比赛环境（1：简体中文赛2：OCG）
    private String getRadioCondition(int checked) {
        if (BaseMethod.notNull(checked + "") && checked == 0) {
            return "1";
        }
        if (BaseMethod.notNull(checked + "") && checked == 1) {
            return "2";
        }
        return "";
    }

    //赛制（1：瑞士轮 2：淘汰赛 3瑞士轮+淘汰赛）
    private String getRadioRule(int checked) {
        if (BaseMethod.notNull(checked + "") && checked == 0) {
            return "1";
        }
        if (BaseMethod.notNull(checked + "") && checked == 1) {
            return "2";
        }
        if (BaseMethod.notNull(checked + "") && checked == 2) {
            return "3";
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    //选择时间
    private void showTimeSelectDialog(TextView textView) {
        BaseMethod.onYearMonthDayTimePicker(CreateGamesActivity.this, new DatePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
                GregorianCalendar gc = new GregorianCalendar();
                gc.set(Calendar.YEAR, Integer.parseInt(year));//设置年
                gc.set(Calendar.MONTH, Integer.parseInt(month) - 1);//这里0是1月..以此向后推
                gc.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));//设置天
                gc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
                gc.set(Calendar.MINUTE, Integer.parseInt(minute));
                Date date = gc.getTime();
                @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String s = format.format(date);
                timeStamp = String.valueOf(date.getTime() / 1000);
                mItemTime.getTextView().setText(s);
            }
        });
    }

    //经纬度
    private void getLatlon(String cityName, String name, String start_at, String players, String cost, String contact, String type, String condition, String rule, String rounds, String winning, String zone_id, String cityid, String countyid) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(mContext);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i == 1000) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                            geocodeResult.getGeocodeAddressList().size() > 0) {

                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                        double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                        String adcode = geocodeAddress.getAdcode();//区域编码

                        LogUtils.d("----->地理编码" + geocodeAddress.getAdcode() + "");
                        LogUtils.d("----->纬度latitude" + latitude + "");
                        LogUtils.d("----->经度longititude" + longititude + "");
                        String s = "latitude:" + latitude + "," + "longititude:" + longititude;
                        JingWeiBean jingWeiBean = new JingWeiBean();
                        jingWeiBean.setLongitude(longititude + "");
                        jingWeiBean.setLatitude(latitude + "");
                        String address_position = gson.toJson(jingWeiBean);
                        shangjiaCreateGameOne(address_position, name, start_at, cityName, players, cost, contact, type, condition, rule, rounds, winning, zone_id, cityid, countyid);
                    } else {
                        ToastUtils.showText(getString(R.string.string_create_game_details_address_error));
                    }
                }
            }
        });
        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName.trim(), "29");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }

    //创建比赛
    private void shangjiaCreateGameOne(String address_position, String name, String start_at, String address, String players, String cost, String contact, String type, String condition, String rule, String rounds, String winning, String zone_id, String cityid, String countyid) {
        showLoadingDialog("");
        PhoneLive.shangjiaCreateGameOne(getUserToken(), name, contact, start_at, players, cost, type, condition, address, address_position, rule, rounds, winning, zone_id, cityid, countyid, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean json = gson.fromJson(response, GeneralBean.class);
                            ToastUtils.showText(json.getMsg());
                            //下一步
                            Intent intent = new Intent(mContext, CreateGamesStepTwoActivity.class);
                            intent.putExtra("name", name);
                            intent.putExtra("contact", contact);
                            intent.putExtra("start_at", start_at);
                            intent.putExtra("players", players);
                            intent.putExtra("address", address);
                            intent.putExtra("cost", cost);
                            intent.putExtra("type", type);
                            intent.putExtra("condition", condition);
                            intent.putExtra("address_position", address_position);
                            intent.putExtra("rule", rule);
                            intent.putExtra("rounds", rounds);
                            intent.putExtra("winning", winning);
                            intent.putExtra("zone_id", zone_id);
                            intent.putExtra("cityid", cityid);
                            intent.putExtra("countyid", countyid);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事创建比赛第一步界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事创建比赛第一步界面");
    }
}
